Template literals, also known as template strings, allow for string interpolation and multiline strings in JavaScript. They provide a more
convenient and flexible way to work with strings compared to traditional string concatenation or manipulation.
Template literals are delimited with the backtick (`)
character. They are a convenient way to include variables or expressions within
a string using placeholders `${expression}`
in the string and evaluate them dynamically.
However, nesting template literals can make the code less readable. With each nested template literal, the code becomes more complex and harder to
understand. It can be challenging to keep track of the opening and closing backticks and properly escape characters if needed.
const color = "red";
const count = 3;
const message = `I have ${color ? `${count} ${color}` : count} apples`; // Noncompliant: nested template strings not easy to read
In such situations, moving the nested template into a separate statement is preferable.
const color = "red";
const count = 3;
const apples = color ? `${count} ${color}` : count;
const message = `I have ${apples} apples`;
The rule makes an exception for nested template literals spanning multiple lines. It allows you to visually separate different sections and gives
you more freedom in formatting your text, including line breaks, indentation, and other formatting elements, enhancing readability.
const name = 'John';
const age = 42;
const message = `Hello ${name}!
You are ${age} years old.
${`This is a nested template literal.`}
It can span multiple lines.`;